/*
 * @Author: 王雁鹏
 * @Date: 2023-04-22 18:06:59
 * @LastEditTime: 2023-04-25 23:58:24
 * @LastEditors: 
 * @Description: 
 * @FilePath: \express\utils\login.js
 * -------------------------------------
 */
const { encode } = require('./encode')
const jsonMine = 'application/json'
const now = Date.now()
function handle(ctx, data, code = 0, message = 'success') {
    ctx.type = jsonMine
    ctx.body = {
        code,
        data,
        message
    }
}
router.get('/login', async (ctx, next) => {
    const { code } = ctx.request.query
    const session = await login(code)
    if (session) {
        const { session_key, openid } = session
        // 查找数据库中是否已经存有openid，如果 hasOpenid 为null说明是新用户
        const hasOpenid = await User.findByPk(openid)
        if (!hasOpenid) {
            // 数据库存储openid,时间戳
            User.create({ openid, timespan: Date.now() })
        }
        handle(ctx, { token: encode(openid) })
    } else {
        throw new Error('登陆失败')
    }
})